package com.mediacloud.app.newsmodule.activity.video

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.util.TypedValue
import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.ViewPager
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.flyco.tablayout.SlidingTabLayout
import com.flyco.tablayout.listener.OnTabSelectListener
import com.jaeger.library.StatusBarUtil
import com.mediacloud.app.assembly.util.load
import com.mediacloud.app.assembly.util.toast
import com.mediacloud.app.assembly.views.BlurTransformation2
import com.mediacloud.app.model.activity.BaseBackActivity
import com.mediacloud.app.model.interfaces.DataInvokeCallBack
import com.mediacloud.app.model.news.ArticleItem
import com.mediacloud.app.model.news.CatalogItem
import com.mediacloud.app.model.news.ReadDataReciver
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.fragment.PagerAdapter
import com.mediacloud.app.newsmodule.fragment.baoliao.api.SpiderCmsApi
import com.mediacloud.app.newsmodule.utils.ReadStatusInvoker
import com.mediacloud.app.reslib.analysis.AnalysisUtils
import com.mediacloud.app.util.ClickUtils
import com.tencent.liteav.demo.superplayer.model.entity.DramaDetailBeanNew
import com.tencent.liteav.demo.superplayer.model.entity.DramaMainBeanNew
import com.tencent.mmkv.MMKV
import com.utils.UriTool
import kotlinx.android.synthetic.main.activity_video_album_detail.*
import kotlinx.android.synthetic.main.layout_broccoli2.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

/**
 * 视频专辑
 */
class VideoAlbumDetailActivity : BaseBackActivity() {
    val titles: MutableList<String> = ArrayList()
    val fragments: MutableList<Fragment> = ArrayList()
    var adapter: PagerAdapter? = null
    var catalogItem: CatalogItem? = null
    var articleItem: ArticleItem? = null
    var spiderCmsApi: SpiderCmsApi.ISpiderCmsApi? = null
    //var shareWarp: ShareWrap? = null
    var data: DramaDetailBeanNew? = null
    override fun getLayoutResID(): Int {
        return R.layout.activity_video_album_detail
    }

    override fun showTitleBar() = false

    override fun getFitSystemWindow() = false


    override fun getStatusBarColor(): Int {
        return Color.TRANSPARENT
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val uriData = intent.data
        if (uriData != null) {
            isFromH5OpenToReStart = UriTool.isFromH5OpenToReStart(this, uriData);
            val articleid: String? =
                uriData.getQueryParameter("articleid")
            val title = uriData.getQueryParameter("title")
            val cname = uriData.getQueryParameter("cname")
            catalogItem = CatalogItem()
            catalogItem?.catname = cname
            articleItem = ArticleItem()
            try {
                articleItem?.title = title
                articleItem?.id = articleid?.toLong() ?: 0
            } catch (e: Exception) {
            }
        } else {
            articleItem = intent.getParcelableExtra("data")
            catalogItem = intent.getParcelableExtra("catalog")
        }
        val componentTitle = intent.getStringExtra("title")
        MMKV.defaultMMKV().encode("127Title",componentTitle)
        spiderCmsApi = SpiderCmsApi.getSpiderCmsApi(this)
        val imgBack = findViewById<View>(R.id.backIv)
        imgBack.setOnClickListener {
            ClickUtils.delayClickable(it)
            finish()
        }
        dealStatusBar(imgBack)

        getDetail()
        readStatus()

        StatusBarUtil.setDarkMode(this)

    }

    private fun dealStatusBar(imgBack: View) {
        val params = imgBack.layoutParams as ConstraintLayout.LayoutParams
        params.topMargin = params.topMargin.coerceAtLeast(StatusBarUtil.getStatusBarHeight(this))
        imgBack.layoutParams = params
    }


    //进来后先去获取一下剧集详情
    private fun getDetail() {
        spiderCmsApi?.sendSeriesAlbumArticleDetail(
            "${articleItem?.getId()}",
            getString(R.string.tenantid)
        )
            ?.enqueue(object :
                Callback<DramaMainBeanNew> {
                override fun onFailure(call: Call<DramaMainBeanNew>, t: Throwable) {
                    toast(t.toString())
                }

                override fun onResponse(
                    call: Call<DramaMainBeanNew>,
                    response: Response<DramaMainBeanNew>
                ) {
                    if (isFinishing || isDestroyed) {
                        return
                    }
                    val body = response.body()
                    if (body!=null&&body.state == 200) {
                        broccoliLayout.visibility = View.GONE
                        body.data?.let {
                            setUi(body.data!!)
                        }

                    }
                }
            })
    }


    private fun readStatus() {
        val readStatusInvoker = ReadStatusInvoker(object : DataInvokeCallBack<ReadDataReciver> {
            override fun success(data: ReadDataReciver) {
                if (isFinishing || isDestroyed) {
                    return
                }
                AnalysisUtils.readsAnalysis(applicationContext, articleItem, data.virtualIncrement)
            }

            override fun fault(data: Any) {
                if (isFinishing || isDestroyed) {
                    return
                }
                AnalysisUtils.readsAnalysis(
                    applicationContext,
                    articleItem,
                    AnalysisUtils.DefaultVirtualIncrement
                )
            }
        })
        readStatusInvoker.readStatistics("${articleItem?.getId()}", 1)
    }



    @SuppressLint("SetTextI18n")
    private fun setUi(dramaDetailBean: DramaDetailBeanNew) {
        this.data = dramaDetailBean
        articleItem?.title = data?.title

        data?.let {
            albumTitleTv.text = it.title
            introTv.text = it.summary
            val logo = it.logo
            articleItem?.logo = logo

            albumLogoIv.load(logo, 0, null)
            val option = RequestOptions()
                .transform(BlurTransformation2(this))
            Glide.with(this).load(logo).apply(option).into(backGroundIv)
            titles.add("选集")
            titles.add("介绍")
            val f = VideoAlbumListFragment()
            val b = Bundle()
            b.putString("AlbumId", "${it.albumId}")
            f.arguments = b
            fragments.add(f)

            val f2 = VideoAlbumIntroduceFragment()
            val b2 = Bundle()
            b2.putString("Intro", it.summary)
            f2.arguments = b2
            fragments.add(f2)
            adapter = PagerAdapter(fragments, titles, supportFragmentManager)
            viewPager.adapter = adapter
            tabLayout.setViewPager(viewPager)

            viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
                override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {

                }

                override fun onPageSelected(position: Int) {
                    if (isFinishing || isDestroyed) {
                        return
                    }
                }

                override fun onPageScrollStateChanged(state: Int) {

                }
            })
            tabLayout.getTitleView(0).setTextSize(TypedValue.COMPLEX_UNIT_SP, 17f)
            tabLayout.setOnTabSelectListener(object : OnTabSelectListener {
                override fun onTabSelect(position: Int) {
                    titles.forEachIndexed { index, _ ->
                        if (index == position)
                            tabLayout.getTitleView(position).setTextSize(TypedValue.COMPLEX_UNIT_SP, 17f)
                        else
                            tabLayout.getTitleView(index).setTextSize(TypedValue.COMPLEX_UNIT_SP, 15f)

                    }
                }

                override fun onTabReselect(position: Int) {
                }

            })
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        MMKV.defaultMMKV().remove("127Title")
        MMKV.defaultMMKV().remove("current_episode")
        MMKV.defaultMMKV().remove("program_episode")

    }
}